package other.game;

import java.util.Arrays;

public class MyArrayList1<T> {

    private Object[] elements;//定义数组保存元素
    private int size;//记录元素个数

    public MyArrayList1() {
        elements = new Object[5];//初始化数组,默认容量5
        size = 0;//默认个数为0
    }
    public void add(T e){
        if(size == elements.length){//判断是否需要扩容
            //扩容为原数组长度的2倍
            elements= Arrays.copyOf(elements,elements.length*2);
        }
        elements[size] = e;
        size++;//以便下次添加元素到下一个
    }
    public T get(int index){
        if(index<0 || index >= size){
            return null;
        }
        return (T) elements[index];
    }
    public void set(int index,T e){
        if (index < 0 || index >= size) {
            //throw new IndexOutOfBoundsException("Index out of bounds: " + index);
            return;
        }
        // 将指定下标的元素设置为指定的新元素
        elements[index] = e;
    }
    public String toString(){
        return Arrays.toString(Arrays.copyOf(elements, size));
    }
}
